package com.tocici.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
//import com.google.protobuf.ServiceException;
//import com.google.protobuf.ServiceException;
import com.tocici.domain.APPLoginUser;
import com.tocici.domain.bo.UserBo;
import com.tocici.domain.bo.UserCateRelationBo;
import com.tocici.domain.vo.CategoryVo;
import com.tocici.domain.vo.UserCateRelationVo;
import com.tocici.domain.vo.UserVo;
import com.tocici.service.ICategoryService;
import com.tocici.service.IUserCateRelationService;
import com.tocici.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginBody;
import org.dromara.common.core.domain.model.PasswordLoginBody;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.service.OssService;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.service.ISysClientService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;


@RestController
@RequestMapping("/app")
@RequiredArgsConstructor
@Slf4j
public class AppLoginAPI {

    private final IUserService userService;

    private final ISysClientService sysClientService;

    private final IUserCateRelationService userCateRelationService;

    private final ICategoryService categoryService;

    private final OssService ossService;


    @SaIgnore
    @PostMapping("/login")
    public R<APPLoginUser> login(@RequestBody String bo){
        LoginBody loginBody = JsonUtils.parseObject(bo, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClientVo client = sysClientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        // 登录
        UserBo body = JsonUtils.parseObject(bo, UserBo.class);
        System.out.println("body = " + body);
        if (body.getPhone() == null){
            return R.fail("手机号不能为空");
        }
        String password = body.getPassword();
        body.setPassword(null);
        List<UserVo> userVos = userService.queryList(body);
        if (userVos.isEmpty()){
            return R.fail("手机号错误");
        }
        if (!BCrypt.checkpw(password,userVos.get(0).getPassword() )){
//            return R.fail("手机号或密码错误");
        }
        UserVo userVo = userVos.get(0);
        APPLoginUser user = BeanUtil.toBean(userVo, APPLoginUser.class);
        System.out.println("userVo = " + userVo);
//        String url = ossService.selectUrlByIds(user.getAvatarUrl().toString());
//        user.setAvatarUrlUrl(url);
        user.setUserId(userVo.getUserId());
        user.setUsername(userVo.getUsername());
        user.setUserType(UserType.APP_USER.getUserType());
        LoginHelper.login(user, new SaLoginModel().setTimeout(60 * 60 * 24).setExtra("clientid",clientId));
        String tokenValue = StpUtil.getTokenValue();
        user.setToken(tokenValue);
        UserCateRelationBo userCateRelationBo = new UserCateRelationBo();
        userCateRelationBo.setUserId(user.getUserId());
        List<UserCateRelationVo> userCateRelationVos = userCateRelationService.queryList(userCateRelationBo);
        List<Long> list = userCateRelationVos.stream().map(UserCateRelationVo::getCateId).toList();

        System.out.println("list = " + list);
        List<CategoryVo> listBatch = Collections.emptyList();
        if (!list.isEmpty()){
            listBatch = categoryService.getListBatch(list);
        }
        user.setCateRelationVos(listBatch);
        return R.ok(user);


    }

    @SaIgnore
    @PostMapping("/register")
    public R register(@RequestBody UserBo bo) {
        System.out.println("bo = " + bo);
        bo.setPassword(BCrypt.hashpw(bo.getPassword()));
        Boolean result = userService.insertByBo(bo);

        return result?R.ok():R.fail();

    }
}
